<template>
	<view class="">
		<NavBar title="我的子账号" :isShowLeftBtn="true">
		</NavBar>
	</view>
	<view class="page" :style="{minHeight:contentHeight}">
		<view class="content">
			<view class="main">
				<view class="main_header flex_both m_b_12">
					<view class="">
						<text class="f_30_0_b">当前：{{roleInfo.role == 1?'集团用户':'普通用户'}}</text>
					</view>
					<view class="main_header_btn" @click="onShowPopup">
						<view class="m_b_10">
							<text class="f_24_f">
								添加子账号
							</text>
						</view>
					</view>
				</view>
				<view class=" flex m_b_20" @click="showCityPicker">
					<view class="m_r_8" style="max-width: 400rpx;">
						<text class="f_26_0 u-line-1">
							{{curAddress}}
						</text>
					</view>
					<view class="m_t_6">
						<up-icon name="arrow-down-fill" size="14" color="#000000"></up-icon>
					</view>
				</view>
				<scroll-view scroll-y="true" :style="{height: viewHeight}" :refresher-threshold="100"
					@scrolltolower="scrolltolowerFun" refresher-enabled="true" refresher-default-style="none">
					<view class="main_list">
						<view class="main_item m_b_28" v-for="(item,index) in storeList" :key="index">
							<view class="main_item_row1 flex_both m_b_42">
								<view class="flex">
									<view class="">
										<text class="f_30_0_b">
											子账号：{{item.nickname}}
										</text>
									</view>
								</view>
								<view class="m_b_4" @click="">
									<text class="f_24_0" style="color: #747474;">
										剩余洗车次数：<text class="f_28_0"
											style="color: #EC2B0B;">{{roleInfo.role == 1?item.car_jituan_num:item.car_normal_num}}次</text>
									</text>
								</view>
							</view>
							<view class="main_item_row2 flex_both">
								<view class="">
									<text class="f_24_0" style="color: #555555;">
										主账号洗车次数：<text class="f_28_0" style="color: #EC2B0B;">{{main_num}}次</text>
									</text>
								</view>
								<view class="flex" style="justify-content: flex-end;">
									<view class="flex">
										<view class="main_item_row2_btn1 m_r_12" @click="onShowDel(index)">
											<text class="f_24_f" style="color: #EC2B0B;">删除账号</text>
										</view>
									</view>
									<view class="flex" v-if="roleInfo.role==1&&item.is_jituan_user">
										<view class="main_item_row2_btn" @click="onShowAddPopup(index)">
											<text class="f_24_f">分配洗车次数</text>
										</view>
									</view>
									<view class="flex" v-if="!roleInfo.role==1">
										<view class="main_item_row2_btn" @click="onShowAddPopup(index)">
											<text class="f_24_f">分配洗车次数</text>
										</view>
									</view>
								</view>
							</view>
						</view>
					</view>
					<view class="empty_box" v-if="!loadShow &&storeList.length ==  0">
						<view class="">
							<up-empty mode="data" icon="http://cdn.uviewui.com/uview/empty/data.png">
							</up-empty>
						</view>
					</view>
					<view class="loading_box m_t_32 " style="padding-bottom: 32rpx;" v-if="loadShow">
						{{ loadMessage }}
					</view>
				</scroll-view>
			</view>
			<view class="">
				<up-popup :show="popupShow" mode="center" round="10" :safeAreaInsetBottom="false">
					<view class="popup_box">
						<view class="popup_title m_b_46">
							<text class="f_30_0_b">
								添加子账号
							</text>
						</view>
						<view class="popup_close" @click="onPopupClose">
							<up-icon name="close" color="#000000" size="17"></up-icon>
						</view>
						<view class="m_b_80">
							<up-input placeholder="请输入手机号" type="number" border="surround" v-model="yqCode"
								inputAlign="left" fontSize="24rpx" :customStyle="{borderColor:'#000000'}"></up-input>
						</view>
						<view class="popup_btn" @click="onPopupOk">
							<view class="m_b_10">
								<text class="f_24_f">
									确定
								</text>
							</view>
						</view>
					</view>
				</up-popup>
				<up-popup :show="AddPopupShow" mode="center" round="10" :safeAreaInsetBottom="false">
					<view class="popup_box" style="width: 586rpx; height: 492rpx;">
						<view class="popup_title m_b_46">
							<text class="f_30_0_b">
								分配次数
							</text>
						</view>
						<view class="popup_close" @click="onAddPopupClose">
							<up-icon name="close" color="#000000" size="17"></up-icon>
						</view>
						<view class="m_b_32 flex" @click="showTypePicker">
							<text class="f_28_0" style="display: inline-block; width: 170rpx;">
								分配类型：
							</text>
							<view class="type_input">
								<view class="" style="max-width: 436rpx;">
									<text class="f_24_f u-line-1" style="color: #303133;" v-if="addForm.car_type">
										{{addForm.type_name}}（剩余：{{addForm.sy_num}}）
									</text>
									<text class="f_24_f u-line-1" style="color: #c0c4cc;" v-else>
										请选择
									</text>
								</view>
							</view>
						</view>
						<view class="m_b_32 flex">
							<text class="f_28_0" style="display: inline-block; width: 170rpx;">
								分配次数：
							</text>
							<up-input placeholder="请输入" border="surround" type="number" v-model="addForm.num"
								inputAlign="left" fontSize="24rpx" :customStyle="{borderColor:'#000000'}"></up-input>
						</view>
						<view class="m_b_80 flex">
							<text class="f_28_0" style="display: inline-block; width: 170rpx;">
								操作类型：
							</text>
							<up-radio-group v-model="addForm.action" placement="row" size="15" activeColor="#FE5E10">
								<up-radio :customStyle="{marginBottom: '8px',marginRight:'6px'}" label="增加" :name="1">
								</up-radio>
								<up-radio :customStyle="{marginBottom: '8px'}" label="减少" :name="0">
								</up-radio>
							</up-radio-group>
						</view>
						<view class="popup_btn" @click="onAddPopupOk">
							<view class="m_b_10">
								<text class="f_24_f">
									确定
								</text>
							</view>
						</view>
					</view>
				</up-popup>
				<up-picker :show="typeShow" :columns="typeColumns" @confirm="typeConfirm" @cancel="typeShow = false"
					keyName="label"></up-picker>
			</view>
		</view>
	</view>
	<up-modal :show="delShow" title="提示" content='即将删除此账号，是否继续？' :show-cancel-button="true" confirm-text="是"
		confirmColor="#F76D11" cancelText="否" @confirm="onDelfirm" @cancel="delShow = false"></up-modal>
	<up-picker ref="uCityPickerRef" :show="cityPickerShow" :columns="cityArr" keyName="name"
		@change="cityPickerChangeHandler" @cancel="cityPickerShow = false" @confirm="cityPickerConfirm"
		:defaultIndex="defaultIndex" confirmColor="#F76D11"></up-picker>
</template>
<script setup lang="ts">
	import { ref, reactive, getCurrentInstance } from "vue";
	import { onLoad, onShow, onReady } from "@dcloudio/uni-app";
	import NavBar from "@/components/navbar.vue"
	import { roleInfoStore } from "@/stores/user.js"
	import QQMapWX from '@/common/qqmap-wx-jssdk.js'
	const { proxy } = getCurrentInstance()
	const contentHeight = ref('100vh')
	const viewHeight = ref()
	const statusBarHeight = ref(88)
	const roleInfo = roleInfoStore()
	onLoad(() => {
		uni.getSystemInfo({
			success: function (info) {
				statusBarHeight.value = (info.statusBarHeight + 44) * 2
				contentHeight.value = `calc(100vh - ${statusBarHeight.value - 6}rpx)`
				viewHeight.value = `calc(100vh - ${statusBarHeight.value + 64 + 76 + 62}rpx)`
			}
		});
		getUserInfo()
	})
	const userInfo = ref({
		group_name: '普通用户'
	})
	const main_num = ref()
	const getUserInfo = async () => {
		let res = await proxy.$http('my.getUserInfo')
		let data = res.data
		userInfo.value = data

	}
	// 账户列表
	const page = ref(1)
	const loadShow = ref(false)
	const loadMessage = ref('加载中')
	const scrolltolowerFun = () => {
		// if (loadShow.value) return
		// page.value = ++page.value;
		// loadShow.value = true;
		// setTimeout(() => {
		// 	getChildInfo()
		// }, 1000)
	}
	const storeList = ref([])
	const getChildInfo = async () => {
		// if (loadMessage.value == '没有更多了') {
		// 	loadShow.value = true;
		// 	setTimeout(() => {
		// 		loadShow.value = false;
		// 	}, 200)
		// 	return
		// }
		let res = await proxy.$http('my.getChildInfo', { page: page.value, ...positionInfo.value })
		let data = res.data
		if (res.code == 1) {
			if (data.length == 0) {
				loadMessage.value = "没有更多了"
			} else {
				storeList.value.push(...data)
			}
		} else {
			loadMessage.value = "加载出错"
		}
		setTimeout(() => {
			loadShow.value = false;
		}, 200)
	}
	// 
	const initTypeList = () => {
		typeColumns.value = [[]]
		if (roleInfo.role == 1) {
			main_num.value = washInfo.value.car_jituan_num
			typeColumns.value[0].push({
				label: '集团车',
				type: 4,
				sy_num: washInfo.value.car_jituan_num
			})
		} else {
			main_num.value = washInfo.value.car_normal_num
			if (washInfo.value.car_normal_type_list.length > 0) {
				washInfo.value.car_normal_type_list.forEach(function (v) {
					typeColumns.value[0].push({
						label: v.type_name,
						type: v.car_type,
						sy_num: v.wash_num
					})
				}, this);

			}
		}
		console.log(typeColumns.value);
	}
	// 删除子账号 
	const delShow = ref(false)
	const delActiveIdx = ref()
	const onShowDel = (e) => {
		delActiveIdx.value = e
		if (roleInfo.role == 1) {
			if (storeList.value[delActiveIdx.value].car_jituan_num > 0) {
				uni.$u.toast('该账号还有次数')
				return
			}
		} else {
			if (storeList.value[delActiveIdx.value].car_num > 0) {
				uni.$u.toast('该账号还有次数')
				return
			}
		}
		delShow.value = true
	}
	const onDelfirm = () => {
		delChildAccount()
		delShow.value = false
	}
	const delChildAccount = async () => {
		let res = await proxy.$http('my.delChildAccount', { id: storeList.value[delActiveIdx.value].id })
		if (res.code == 1) {
			uni.$u.toast('删除成功')
			setTimeout(() => {
				storeList.value = []
				getChildInfo()
			}, 800)
		}
	}
	// 划分次数弹窗
	const AddPopupShow = ref(false)
	const addForm = ref({
		car_type: '',
		type_name: '',
		sy_num: '',
		num: '',
		action: 1
	})
	const addActiveIdx = ref()
	const onShowAddPopup = (e) => {
		addActiveIdx.value = e
		AddPopupShow.value = true
	}
	const onAddPopupClose = () => {
		AddPopupShow.value = false
		addForm.value = {
			car_type: '',
			type_name: '',
			sy_num: '',
			num: '',
			action: 1
		}
	}
	const onAddPopupOk = () => {
		if (addForm.value.car_type == '') {
			uni.$u.toast('类型不能为空')
			return
		}
		if (addForm.value.num == '') {
			uni.$u.toast('次数不能为空')
			return
		}
		AddPopupShow.value = false
		toChildNum()
	}
	// 次数划分
	const toChildNum = async () => {
		let params = {
			to_user_id: storeList.value[addActiveIdx.value].id,
			car_type: addForm.value.car_type,
			num: parseInt(addForm.value.num)
		}
		if (!addForm.value.action) {
			params.num = params.num * -1
		}
		let res = await proxy.$http('my.toChildNum', { ...params, ...positionInfo.value })
		if (res.code == 1) {
			uni.$u.toast('分配成功')
			setTimeout(() => {
				loadMessage.value = '加载中'
				page.value = 1
				storeList.value = []
				getChildInfo()
				getUserInfo()
				getWashNum()
				addForm.value = {
					car_type: '',
					type_name: '',
					sy_num: '',
					num: '',
					action: 1
				}
			}, 800)

		}
	}
	// 类型选择
	const typeShow = ref(false)
	const typeColumns = ref([[]])
	const showTypePicker = () => {
		typeShow.value = true
	}
	const typeConfirm = (e) => {
		addForm.value.car_type = e.value[0].type
		addForm.value.type_name = e.value[0].label
		addForm.value.sy_num = e.value[0].sy_num
		typeShow.value = false
		// console.log(e.value[0].type);
	}
	// 绑定账号
	const popupShow = ref(false)
	const yqCode = ref()
	const onShowPopup = () => {
		popupShow.value = true
	}
	const onPopupClose = () => {
		popupShow.value = false
	}
	const onPopupOk = () => {
		if (!yqCode.value) {
			uni.$u.toast('手机号码不能为空')
			return
		}
		popupShow.value = false
		bindChildAccount()
	}
	const bindChildAccount = async () => {

		let res = await proxy.$http('my.bindChildAccount', { phone: yqCode.value })
		yqCode.value = ''
		if (res.code == 1) {
			uni.$u.toast('绑定成功')
			setTimeout(() => {
				loadMessage.value = '加载中'
				page.value = 1
				storeList.value = []
				getChildInfo()
			}, 800)
		}
	}
	// 区县相关
	const qqmapsdk = ref(null)
	onReady(() => {
		qqmapsdk.value = new QQMapWX({
			key: proxy.$config.txMapKey
		});
		getLoaction()
	})
	const longitude = ref()
	const latitude = ref()

	const getLoaction = () => {
		uni.getLocation({
			type: 'gcj02', // 返回可以用于uni.openLocation的经纬度
			success: function (res) {
				longitude.value = res.longitude
				latitude.value = res.latitude
				qqmapsdk.value.reverseGeocoder({
					location: {
						latitude: res.latitude,
						longitude: res.longitude
					},
					success: (res2) => {
						console.log(res2);
						// let data = res2.result.address_component
						// curAddress.value = res2.result.formatted_addresses.standard_address
						// console.log(data);
						// getDistrictByCityId(res2)
						// 获取区id
						getNowAreaByName(res2.result)
					},
					fail: (e) => {
						console.log(e, 'eee')
					}
				})

				// 获取附近房屋
			},
			fail: function (e) {
				// uni.setStorageSync('position_info', { code: 2, longitude: 0, latitude: 0 })
				console.log('获取位置信息失败：' + JSON.stringify(e));
			}
		});
	}
	const getNowAreaByName = async (e) => {
		let res = await proxy.$http("common.getNowAreaByName", { area_name: e.address_component.district, city_name: e.address_component.city })
		let data = res.data
		curAddress.value = data.province.name + '-' + data.cityInfo.name + '-' + data.areaInfo.name
		initCity(res.data)
	}
	// 区县相关
	const cityPickerShow = ref(false)
	const uCityPickerRef = ref(null)
	const rawCityData = ref([])
	const cityArr = ref([])
	const curAddress = ref('')
	const defaultIndex = ref([0, 3, 2])
	const positionInfo = ref({
		province_name: '',
		city_name: '',
		area_name: ''

	})
	const initCity = async (e) => {
		try {
			let res = await proxy.$http('common.getAreaAll')
			if (res.code === 1) {
				defaultIndex.value = []
				rawCityData.value = res.data
				positionInfo.value.province_name = e.province.name
				positionInfo.value.city_name = e.cityInfo.name
				positionInfo.value.area_name = e.areaInfo.name
				const provinceList = rawCityData.value.map(item => {
					return { name: item.name, id: item.id }
				})
				let provinceIndex = 0
				provinceList.forEach((v, index) => {
					if (v.id == e.province.id) {
						provinceIndex = index
						defaultIndex.value.push(index)
					}
				})
				const cityList = rawCityData.value[provinceIndex].children.map(item => {
					return { name: item.name, id: item.id }
				})
				let cityIndex = 0
				cityList.forEach((v, index) => {
					if (v.id == e.cityInfo.id) {
						defaultIndex.value.push(index)
						cityIndex = index
					}
				})
				const counties = rawCityData.value[provinceIndex].children[cityIndex].children.map(item => {
					return { name: item.name, id: item.id }
				})
				counties.forEach((v, index) => {
					if (v.id == e.areaInfo.id) {
						defaultIndex.value.push(index)
					}
				})
				console.log(defaultIndex.value);
				cityArr.value.push(provinceList, cityList, counties)
				getWashNum()
				getChildInfo()
			} else {
				throw new Error(res.msg)
			}
		} catch (e) {
			uni.showToast({
				icon: 'none',
				title: e.message
			})
		}
	}
	const showCityPicker = () => {
		cityPickerShow.value = true
	}
	const cityPickerChangeHandler = (e) => {
		const { columnIndex, indexs } = e
		if (columnIndex === 0) {
			uCityPickerRef.value.setColumnValues(1, rawCityData.value[indexs[0]].children);
			uCityPickerRef.value.setColumnValues(2, rawCityData.value[indexs[0]].children[0].children);
		}
		if (columnIndex === 1) {
			uCityPickerRef.value.setColumnValues(2, rawCityData.value[indexs[0]].children[indexs[1]].children);
		}
	}
	const cityPickerConfirm = (e) => {
		const arr = []
		arr.push(e.value[0].name)
		arr.push(e.value[1].name)
		arr.push(e.value[2].name)
		curAddress.value = arr.join('-')
		positionInfo.value.province_name = e.value[0].name
		positionInfo.value.city_name = e.value[1].name
		positionInfo.value.area_name = e.value[2].name
		cityPickerShow.value = false
		getWashNum()
		getChildInfo()
	}
	const washInfo = ref({
		car_jituan_num: 0,
		car_jituan_type_list: [],
		car_normal_num: 0,
		car_normal_type_list: []
	})
	const getWashNum = async () => {
		let res = await proxy.$http('my.getWashNum', { user_id: userInfo.value.id, ...positionInfo.value })
		if (res.code == 1) {
			washInfo.value = res.data
			initTypeList()
		}
	}
</script>
<style lang="scss" scoped>
	.page {
		background: #F7F8FC;
	}

	.content {
		padding: 20rpx;

		.main {
			.main_header {
				.main_header_btn {
					width: 176rpx;
					height: 53rpx;
					background: #F93F1A;
					border-radius: 27rpx;
					display: flex;
					align-items: center;
					justify-content: center;
				}
			}

			.main_list {
				.main_item {
					padding: 24rpx;
					padding-bottom: 20rpx;
					background: #FFFFFF;
					box-shadow: 2rpx 7rpx 5rpx 0rpx rgba(197, 197, 197, 0.29);
					border-radius: 6rpx;

					.main_item_row2 {
						.main_item_row2_input {
							padding: 6rpx 12rpx;
							border: 2rpx solid #D4D4D4;
							border-radius: 10rpx 0 0 10rpx;
						}

						.main_item_row2_btn1 {
							width: 136rpx;
							height: 58rpx;
							border-radius: 10rpx;
							border: 2rpx #F93F1A solid;
							display: flex;
							align-items: center;
							justify-content: center;
						}

						.main_item_row2_btn {
							width: 176rpx;
							height: 62rpx;
							border-radius: 10rpx;
							background: #F93F1A;
							display: flex;
							align-items: center;
							justify-content: center;
						}
					}
				}
			}
		}

		.popup_box {
			width: 486rpx;
			height: 291rpx;
			padding: 46rpx;
			padding-top: 36rpx;
			background: #FFFFFF;
			border-radius: 10rpx;
			position: relative;

			.popup_title {
				text-align: center;
			}

			.popup_close {
				position: absolute;
				top: 18rpx;
				right: 18rpx;
				padding: 6rpx;
			}

			.popup_btn {
				margin: 0 auto;
				width: 261rpx;
				height: 63rpx;
				background: #F93F1A;
				border-radius: 10rpx;
				display: flex;
				align-items: center;
				justify-content: center;
			}
		}
	}

	.type_input {
		display: flex;
		flex-direction: row;
		align-items: center;
		justify-content: space-between;
		flex: 1;
		border-width: 0.5px !important;
		border-color: #dadbde !important;
		border-style: solid;
		padding-top: 10px;
		padding-bottom: 10px;
		padding-left: 9px;
		padding-right: 9px;
		border-radius: 4px;
	}
</style>